package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    public void run(){
        try{
            String method;
            String url;
            String protocol;

            String line = readLine();
            System.out.println(line);

            String[]data = line.split("\\s");
            method = data[0];
            url =data[1];
            protocol = data[2];
            System.out.println("method"+method);
            System.out.println("url"+url);
            System.out.println("protocol"+protocol);

            Map<String,String > handers = new HashMap<>();
            while(!(line = readLine()).isEmpty()){
                System.out.println("消息头"+line);
                data = line.split(":\\s");
                handers.put(data[0],data[1]);
            }
            System.out.println("handers"+handers);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    private String readLine() throws IOException{
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        int d ;
        char pre = 'a';
        char cur = 'a';
        while((d = in.read())!=-1){
            cur = (char)d;
            if(pre == 13 && cur == 10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }
}
